package edu.sandau.basic.controller;

import edu.sandau.basic.domain.User;
import edu.sandau.basic.global.GlobalEnum;
import edu.sandau.basic.mapper.UserExtMapper;
import edu.sandau.basic.mapper.UserMapper;
import edu.sandau.basic.service.UserService;
import edu.sandau.basic.vo.BasicMsg;
import edu.sandau.basic.vo.BasicMsgWithData;
import edu.sandau.basic.vo.UserPatchVo;
import edu.sandau.basic.vo.UserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import edu.sandau.basic.utils.Converter;


import java.time.LocalDate;
import java.util.Date;
import java.util.Map;

import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "用户管理", description = "用户的增删改查接口")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserExtMapper userExtMapper;

    @Resource
    private UserService userService;

    //  列表（支持按用户名和启用状态过滤）
    @GetMapping("/users")
    @Operation(summary = "List users.")
    public BasicMsgWithData<List<User>> getUsers(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Boolean isActive) {
        List<User> list = userService.listUsers(username, isActive);
        return new BasicMsgWithData<>(list);
    }

    //  详情
    @GetMapping("/users/{id}")
    @Operation(summary = "Get user detail.")
    public BasicMsgWithData<User> getUser(@PathVariable Integer id) {
        User u = userService.getById(id);
        BasicMsgWithData<User> msg = new BasicMsgWithData<>(u);
        if (u == null) {
            msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
            msg.setErrorMsg("用户不存在");
        } else {
            msg.setErrorCode(GlobalEnum.ErrorCode.OK);
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        }
        return msg;
    }

    //  新增
    @PostMapping("/user")
    @Operation(summary = "Add a new user.")
    public BasicMsg addUser(@RequestBody UserVo user){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.addUser(user);
        msg.setErrorCode(errorCode);
        msg.setOperationResult(errorCode == GlobalEnum.ErrorCode.OK ?
                GlobalEnum.OperationResult.SUCC : GlobalEnum.OperationResult.UNSUCC);
        msg.setErrorMsg(errorCode == GlobalEnum.ErrorCode.OK ? "添加用户成功。" : "添加用户失败。");
        return msg;
    }

    //  更新
    @PutMapping("/users/{id}")
    @Operation(summary = "Update user.")
    public BasicMsg updateUser(@PathVariable Integer id, @RequestBody UserVo user){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.updateUser(id, user);
        msg.setErrorCode(errorCode);
        msg.setOperationResult(errorCode == GlobalEnum.ErrorCode.OK ?
                GlobalEnum.OperationResult.SUCC : GlobalEnum.OperationResult.UNSUCC);
        msg.setErrorMsg(errorCode == GlobalEnum.ErrorCode.OK ? "修改成功。" : "修改失败。");
        return msg;
    }

    @PatchMapping("/users/{id}")
    @Operation(summary = "部分更新用户信息", description = "可单独修改 name、enname、password、mobile、email、birthday、profileUrl 等字段")
    public BasicMsg patchUser(@PathVariable Integer id, @RequestBody UserPatchVo updates) {
        // 1. 从数据库获取现有用户
        User db = userMapper.selectByPrimaryKey(id);
        if (db == null) {
            return BasicMsg.error("用户不存在");
        }

        // 2. 按照传入字段逐一判断并更新
        if (updates.getUserName() != null) {
            db.setUsername(updates.getUserName());
        }
        if (updates.getEnname() != null) {
            db.setEnName(updates.getEnname());
        }
        if (updates.getPassword() != null) {
            db.setPassword(updates.getPassword());
        }
        if (updates.getMobile() != null) {
            db.setMobile(updates.getMobile());
        }
        if (updates.getEmail() != null) {
            db.setEmail(updates.getEmail());
        }
        if (updates.getBirthday() != null) {
            try {
                // birthday 可能是 LocalDate 或 String，根据 UserPatchVo 的类型
                db.setBirthday(Converter.localDateToDate(updates.getBirthday()));
            } catch (Exception e) {
                return BasicMsg.error("生日格式应为 yyyy-MM-dd");
            }
        }
        if (updates.getProfileUrl() != null) {
            db.setProfileUrl(updates.getProfileUrl());
        }

        if (updates.getIsActive() != null) {
            db.setIsActive(updates.getIsActive());
        }




        // 3. 系统字段更新
        db.setUpdatetime(new Date());
        db.setUpdateperson(1);

        // 4. 更新数据库
        int rows = userExtMapper.updateByPrimaryKeySelective(db);
        return rows == 1 ? BasicMsg.ok("部分信息更新成功") : BasicMsg.error("更新失败");
    }


    //  删除
    @DeleteMapping("/users/{id}")
    @Operation(summary = "Delete user.")
    public BasicMsg deleteUser(@PathVariable Integer id){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.deleteUser(id);
        msg.setErrorCode(errorCode);
        msg.setOperationResult(errorCode == GlobalEnum.ErrorCode.OK ?
                GlobalEnum.OperationResult.SUCC : GlobalEnum.OperationResult.UNSUCC);
        msg.setErrorMsg(errorCode == GlobalEnum.ErrorCode.OK ? "删除成功。" : "删除失败。");
        return msg;
    }

    // 已有：登录
    @PostMapping("/login")
    @Operation(summary = "Login.")
    public BasicMsg login(@RequestBody UserVo user){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.userLogin(user.getUserName(), user.getPassword());
        msg.setErrorCode(errorCode);
        if(errorCode == GlobalEnum.ErrorCode.OK){
            msg.setErrorMsg("用户登录成功。");
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        }else{
            msg.setErrorMsg("用户登录失败。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }
}
